import logging
import re
import jwt
import uuid
import datetime
from django.contrib.auth import authenticate, login, logout
from django.db import DatabaseError
from requests import models
from rest_framework.views import APIView



logger = logging.getLogger('django')
from .models import User
from django.shortcuts import redirect
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseForbidden, JsonResponse
# Create your views here.
from django.views import View
from rest_framework.response import Response


# Create your views here.
#
# class LoginView(View):
#     def get(self, request):
#         return render(request, 'login.html')
#
#     def post(self, request):
#         username = request.POST.get('username')
#         password = request.POST.get('password')
#         remembered = request.POST.get('remembered')
#         if not all([username, password]):
#             return HttpResponseForbidden('缺少必传参数')
#         if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
#             return HttpResponseForbidden('请输入正确用户名或手机号')
#         if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
#             return HttpResponseForbidden('密码最少8为 最长20位')
#         user = authenticate(username=username, password=password)
#         if user is None:
#             return render(request, 'login.html', {'account_errmsg': '账号或密码问题'})
#         login(request, user)
#         if remembered != 'on':
#             request.session.set_expiry(0)
#         else:
#             request.session.set_expiry(None)
#         response = redirect(reverse('contents:index'))
#         response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
#         return response
#
#
# class RegisterView(View):
#     def get(self, request):
#         return render(request, 'register.html')
#         # 提供用户注册页面
#
#     def post(self, request):
#         username = request.POST.get('username')
#         password = request.POST.get('password')
#         password2 = request.POST.get('password2')
#         mobile = request.POST.get('mobile')
#         allow = request.POST.get('allow')
#         if not all([username, password, password2, mobile, allow]):
#             return HttpResponseForbidden('缺少必传参数')
#         if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
#             return HttpResponseForbidden('请输入5-20个字符的用户名')
#         if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
#             return HttpResponseForbidden('请输入8-20位的密码')
#         if password != password2:
#             return HttpResponseForbidden('两次密码不一致')
#         if not re.match(r'^1[3-9]\d{9}', mobile):
#             return HttpResponseForbidden('请输入正确的手机号码')
#         if allow != 'on':
#             return HttpResponseForbidden('请勾选用户协议')
#         try:
#             User.objects.create_user(username=username, password=password, mobile=mobile)
#         except DatabaseError:
#             return render(request, 'register.html', {'register_errmsg': '注册失败'})
#         return redirect(reverse("contents:index"))
#
#
# class UsernameCountView(View):
#     def get(self, request, username):
#         count = User.objects.filter(username=username).count()
#         return JsonResponse({'code': 200, 'errmsg': 'OK', 'count': count})
#
#
# class MobileCountView(View):
#     def get(self, request, mobile):
#         count = User.objects.filter(mobile=mobile).count()
#         return JsonResponse({'code': 200, 'errmsg': 'OK', "count": count})
#
#
# class LogoutView(View):
#     def get(self, request):
#         logout(request)
#         response = redirect(reverse('contents:index'))
#         response.delete_cookie('username')
#         return response


# 密钥，用于签名和验证JWT
# secret_key = 'your-secret-key'
#
# payload = {
#     'user_id': 123,
#     'username': 'john',
# }
#
# # 自定义过期时间为10分钟后
# expiration_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
#
# # 生成JWT并指定算法和额外的头部信息
# token = jwt.encode(payload, secret_key, algorithm='HS256', headers={'kid': 'key-id'}, exp=expiration_time)
# print('Generated JWT:', token)
#
#
# # 模拟用户登录，生成JWT
# def generate_jwt(user_id, username):
#     payload = {'user_id': user_id, 'username': username}
#     return jwt.encode(payload, secret_key, algorithm='HS256')
#
#
# # 模拟用户访问需要认证的资源，验证JWT
# def verify_jwt(received_token):
#     try:
#         decoded_payload = jwt.decode(received_token, secret_key, algorithms=['HS256'])
#         print('User ID:', decoded_payload['user_id'])
#         print('Username:', decoded_payload['username'])
#     except jwt.ExpiredSignatureError:
#         print('JWT has expired.')
#     except jwt.InvalidTokenError:
#         print('Invalid JWT.')
#
#
# user_token = generate_jwt(123, 'john')
# verify_jwt(user_token)
# class LoginView(APIView):
#     """用户登录"""
#
#     def post(self, request, *args, **kwargs):
#         user = request.data.get('username')
#         pwd = request.data.get('password')
#
#         user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
#         if not user_object:
#             return Response({'code': 1000, 'error': '用户名或密码错误'})
#
#         random_string = str(uuid.uuid4())
#
#         user_object.token = random_string
#
#         user_object.save()
#         return Response({'code': 1001, 'data': random_string})
#
#
# class OrderView(APIView):
#     def get(self, request, *args, **kwargs):
#         token = request.query_params.get('token')
#         if not token:
#             return Response({'code': 2000, 'error': '登录成功之后才能访问'})
#         user_object = models().UserInfo.object.filter(token=token).first()
#         if not user_object:
#             return Response({'code': 2000, 'error': 'token无效'})
#         return Response('订单列表')
#

# class JwtLoginView(APIView):
#     """用户登录"""
#
#     def post(self, request, *args, **kwargs):
#         user = request.data.get('username')
#         pwd = request.data.get('password')
#
#         user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
#         if not user_object:
#             return Response({'code': 1000, 'error': '用户名或密码错误'})
#
#         import jwt
#         import datetime
#         salt = 'asbibbfqwdas11a321sas1asdaa2d1s'
#         # 构造header
#         headers = {
#             'typ': 'jwt',
#             'alg': 'HS256'
#         }
#         # 构造payload
#         payload = {
#             'user_id': user_object.id,  # 自定义用户ID
#             'username': user_object.username,  # 自定义用户名
#             'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
#         }
#
#         token = jwt.encode(payload=payload, key=salt, algorithm='HS256', headers=headers).decode('utf-8')
#         return Response({'code': 1001, 'data': token})


# class JwtOrderView(APIView):
#     def get(self, request, *args, **kwargs):
#         # 获取token并判断token的合法性
#         token = request.query_params.get('token')
#
#         import jwt
#         from jwt import exceptions
#         salt = 'asbibbfqwdas11a321sas1asdaa2d1s'
#         payload = None
#         msg = None
#         try:
#             verified_payload = jwt.decode(token, salt, True)
#         except exceptions.ExpiredSignatureError:
#             msg = 'token已经失效'
#         except jwt.DecodeError:
#             msg = 'token认证失效'
#         except jwt.InvalidTokenError:
#             msg = '非法的token'
#         if not payload:
#             return Response({'code': 1003, 'error': msg})
#
#         print(payload['user_id'], payload['username'])
#         return Response('订单列表')





from .utils.jwt_auth import create_token

class ProLoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')
        user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if not user_object:
            return Response({'code': 1000, 'error': '用户名或密码错误'})
        token = create_token({'id': user_object.id, 'name': user_object.username})

        return Response({'code': 1001, 'data': token})


class ProOrderView(APIView):

    def get(self, request, *args, **kwargs):
        print(request.user)
        return Response('订单列表')
